// attractInvestment/pages/addIDcard/addIDcard.js
// pages/main/main.js
import config from '../../config'
const API = config.api
const app = getApp()
import {
    phoneFun,
    isDateYYYYDDMM,
    checkIdCard,
    checkHKMacao,
    IdentityCodeValid,
    isChineseName
} from '../../utils/util'
import { getLessLimitSizeImage } from '../../utils/imageFile'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        showMask: false,
        isShowRepeatConfirmation: false,
        agentBackImgUrl: "", //证件反面照 阿里云返回
        agentBackImg: "", //证件反面照 粤通卡图片链接
        agentFrontImgUrl: "", //证件正面照 调用阿里云图片上传返回图片路径
        agentFrontImg: "", //证件正面照 粤通卡图片链接
        taiWan_BackImgUrl: '', //台胞证背面阿里云返回
        taiWan_BackImg: '', //台胞证背面粤通卡图片链接
        taiWan_FrontImgUrl: '', //台胞证 阿里云返回
        taiWan_FrontImg: '', //台胞证 粤通卡图片链接
        KO_FrontImg: '', //港澳证 粤通卡图片链接
        KO_FrontImgUrl: '', //港澳证 阿里云返回
        KO_BackImg: '', //港澳证背面 粤通卡图片链接
        KO_BackImgUrl: '', //港澳证背面 阿里云返回
        agentBackImgAliYun_success: 0,
        taiwanImgAliYun_success: 0,
        taiwanImgAliYun_back_success: 0,
        HongKongAndMacao_success: 0,
        HongKongAndMacao_back_success: 0,
        agentFrontImgAliYun_success: 0,
        // 收货地址信息
        phone: '',//代办人手机号
        interval: null,
        remindernum: 5,
        certifiType: 1,
        idcardData: {
            name: '',
            num: '',
            taiWanName: '',
            taiWanNum: '',
            HongKongAndMacaoName: '',
            HongKongAndMacaonNum: '',
        },
    },
    BackPage() {
        wx.navigateBack({
            delta: 1
        });
    },
    close() {
        this.setData({
            isShowRepeatConfirmation: false,
            showMask: false
        })
    },
	//获取用户状态
	getState() {
		if (!this.data.lock) {
			wx.showLoading({
				title: '加载中...',
				mask: true
			});
			this.data.lock = true;
			app.http(API.apiGetState, {
				userId: this.data.userId
			}).then(res => {
				console.log(res)
				if (res.code == 200) {
					let rspData = JSON.parse(res.rspData);
					console.log(rspData)
					var etcInfo = !rspData.jsonData || rspData.jsonData == '' ? '' : JSON.parse(rspData.jsonData)

					if (rspData.state < 4) {
						this.setData({
							phone: rspData.phone ? rspData.phone : '',
							state: rspData.state,
							vehiclePlate: rspData.vehiclePlate,
							vehicleColor: rspData.vehicleColor,
							etcInfo: etcInfo,
							ownerType: rspData.etcUserType,
							submitOrderStatus: etcInfo.submitOrderStatus == 1 ? 1 : 0
						}, () => {
							if (this.data.submitOrderStatus == 1) {
								this.toBingBank();
							}
							wx.hideLoading();
						})

					} else {
						wx.redirectTo({
							url: '/pages/submit_success/submit_success',
						})

						wx.hideLoading();

					}

				} else {
					wx.hideLoading();
				}
				this.data.lock = false
			}).catch(err => {
				console.log(err)
				wx.hideLoading();
				this.data.lock = false
			})
		}
	},
    submission() {
        var agentName = '';
        if (this.data.certifiType == 1) {
            agentName = this.data.idcardData.name;
            let codeValid = IdentityCodeValid(this.data.idcardData.num)
            // let codeValid = true
            if (this.data.agentFrontImgAliYun_success != 2) {
                wx.showToast({
                    title: '请上传身份证正面',
                    icon: 'none',
                    image: '',
                    duration: 3000
                });
                return;
            }
            if (this.data.agentBackImgAliYun_success != 2) {
                wx.showToast({
                    title: '请上传身份证背面',
                    icon: 'none',
                    image: '',
                    duration: 3000
                });
                return;
            }
            if (this.data.idcardData.name == '') {
                wx.showToast({
                    title: '请核对身份证姓名',
                    icon: 'none',
                    image: '',
                    duration: 3000
                });
                return;
            }
            if (this.data.idcardData.num == '' || !codeValid) {
                wx.showToast({
                    title: '请核对身份证号',
                    icon: 'none',
                    image: '',
                    duration: 3000
                });
                return;
            }
        } else if (this.data.certifiType == 10) {
            agentName = this.data.idcardData.HongKongAndMacaoName
            let codeValid = checkHKMacao(this.data.idcardData.HongKongAndMacaonNum);
            if (this.data.HongKongAndMacao_success != 2) {
                wx.showToast({
                    title: '请上传证件正面照',
                    icon: 'none',
                    image: '',
                    duration: 3000
                });
                return;
            }
            if (this.data.HongKongAndMacao_back_success != 2) {
                wx.showToast({
                    title: '请上传证件背面照',
                    icon: 'none',
                    image: '',
                    duration: 3000
                });
                return;
            }
            if (this.data.idcardData.HongKongAndMacaoName == '') {
                wx.showToast({
                    title: '请输入客户姓名',
                    icon: 'none',
                    image: '',
                    duration: 3000
                });
                return;
            }
            if (this.data.idcardData.HongKongAndMacaonAddress == '') {
                wx.showToast({
                    title: '请填写通讯地址',
                    icon: 'none',
                    image: '',
                    duration: 3000
                });
                return;
            }
            if (!codeValid.errCode) {
                wx.showToast({
                    title: codeValid.errMsg,
                    icon: 'none',
                    image: '',
                    duration: 3000
                });
                return;
            }
        } else if (this.data.certifiType == 11) {
            agentName = this.data.idcardData.taiWanName
            let codeValid = checkIdCard(this.data.idcardData.taiWanNum);

            if (this.data.taiwanImgAliYun_success != 2) {
                wx.showToast({
                    title: '请上传证件正面照',
                    icon: 'none',
                    image: '',
                    duration: 3000
                });
                return;
            }
            if (this.data.taiwanImgAliYun_back_success != 2) {
                wx.showToast({
                    title: '请上传证件背面照',
                    icon: 'none',
                    image: '',
                    duration: 3000
                });
                return;
            }
            if (this.data.idcardData.taiWanName == '') {
                wx.showToast({
                    title: '请输入客户姓名',
                    icon: 'none',
                    image: '',
                    duration: 3000
                });
                return;
            }
            if (this.data.idcardData.taiWanAddress == '') {
                wx.showToast({
                    title: '请填写通讯地址',
                    icon: 'none',
                    image: '',
                    duration: 3000
                });
                return;
            }
            if (codeValid.respCode != 0) {
                wx.showToast({
                    title: codeValid.respDesc,
                    icon: 'none',
                    image: '',
                    duration: 3000
                });
                return;
            }
        }
        if (!isChineseName(agentName)) {
            wx.showToast({
                title: '请输入合法的客户姓名',
                icon: 'none',
                image: '',
                duration: 3000
            });
            return;
        }
        if (!phoneFun(this.data.phone)) {
            wx.showToast({
                title: '请输入正确的手机号码',
                icon: 'none',
                image: '',
                duration: 3000
            });
            return;
        }
        if (!isDateYYYYDDMM(this.data.idcardData.trx_id_stime)) {
            wx.showToast({
                title: '请输入正确的证件起始时间（例：20210303）',
                icon: 'none',
                image: '',
                duration: 3000
            });
            return;
        }
        if (!isDateYYYYDDMM(this.data.idcardData.trx_id_etime)) {
            wx.showToast({
                title: '请输入正确的证件结束时间（例：20210303）',
                icon: 'none',
                image: '',
                duration: 3000
            });
            return;
        }
        this.setData({
            isShowRepeatConfirmation: true,
            showMask: true,
        })
    },
    //添加用户信息
    authenticationInfo() {
        var certifiNo = '';
        var agentName = '';
        var address = '';
        var agentBackImgUrl = '';
        var agentFrontImgUrl = '';
        var idcard_pic_url1 = '';
        var idcard_pic_url2 = '';
        if (this.data.certifiType == 1) {
            agentBackImgUrl = this.data.agentBackImgUrl;
            idcard_pic_url2 = this.data.agentBackImg;
            idcard_pic_url1 = this.data.agentFrontImg;
            agentFrontImgUrl = this.data.agentFrontImgUrl;
            certifiNo = this.data.idcardData.num;
            address = this.data.idcardData.address;
            agentName = this.data.idcardData.name;
        } else if (this.data.certifiType == 10) {
            agentBackImgUrl = this.data.KO_BackImgUrl;
            agentFrontImgUrl = this.data.KO_FrontImgUrl;
            idcard_pic_url2 = this.data.KO_BackImg;
            idcard_pic_url1 = this.data.KO_FrontImg;
            certifiNo = this.data.idcardData.HongKongAndMacaonNum
            agentName = this.data.idcardData.HongKongAndMacaoName
            address = this.data.idcardData.HongKongAndMacaonAddress
        } else {
            certifiNo = this.data.idcardData.taiWanNum
            agentName = this.data.idcardData.taiWanName
            address = this.data.idcardData.taiWanAddress
            agentBackImgUrl = this.data.taiWan_BackImgUrl;
            agentFrontImgUrl = this.data.taiWan_FrontImgUrl;
            idcard_pic_url2 = this.data.taiWan_BackImg;
            idcard_pic_url1 = this.data.taiWan_FrontImg;
        }
        wx.showLoading({
            title: '正在提交资料',
            mask: true,
        });
        if (this.data.idcardData.trx_id_etime == "长期") {
            this.data.idcardData.trx_id_etime = '20990101'
        }
        var parmas = {
            address: address,//地址
            idcard_pic_url2: idcard_pic_url2,//证件背面照
            idcard_pic_url1: idcard_pic_url1,//证件证明照
            idnum: certifiNo,//证件号码
            idtype: this.data.certifiType,//证件类型
            organ: agentName,//客户名称
            user_type: 8,//用户类型。固定个人为8
            mobilephone: this.data.phone,//用户手机号码
            trx_id_etime: this.data.idcardData.trx_id_etime,//证件结束日期
            trx_id_stime: this.data.idcardData.trx_id_stime,//证件开始日期
            userId: this.data.userId,
            applyExtInfo: {
                agentBackImgUrl,
                agentFrontImgUrl,
            }
        }
        app.http(API.apiSaveAccountInfoRequest, parmas).then(res => {

            if (res.code == 200) {
                wx.redirectTo({
                    url: '/pages/drivingLicense/drivingLicense'
                })
                wx.hideLoading();
            } else {
                wx.showModal({
                    title: '提示',
                    content: res.message || '提交失败',
                    confirmColor: '#005866',
                    showCancel: false,
                    success(res) { }
                })
                wx.hideLoading();
                this.close()

            }

        }).catch(err => {
            wx.hideLoading();
            this.close()
        })

    },
    onInput(e) {
        let type = e.target.dataset.type;
        let value = e.detail.value;

        this.setData({
            [type]: value.replace(/\s+/g, "")
        })
    },
    //阿里云上传
    ossUploadFile(img) {
        return new Promise((resolve, reject) => {
            wx.getFileSystemManager().readFile({
                filePath: img,
                encoding: 'base64',
                success: (result) => {
                    var rawBase64 = result.data;
                    app.http(API.apiUploadOss, {
                        image: rawBase64,
                        user_id: this.data.userId
                    }).then(res => {
                        // console.log(res);
                        resolve(res)
                    }).catch(err => {
                        console.log(err);
                        reject(err)
                    })
                }, fail: err => {
                    console.log(err);
                    reject(err)
                },
            })

        })
    },
    //身份证图片上传
    idCardLicenseImage(ocrVehicleType, type, side, tempFilePaths) {
        this.setData({
            [type]: 1,
        });
        this.ossUploadFile(tempFilePaths).then(ossRes => {
            if (ossRes.code == 200) {
                getLessLimitSizeImage('pressCanvas', tempFilePaths, 1, '750', (e) => {
                    wx.getFileSystemManager().readFile({
                        filePath: e,
                        encoding: 'base64',
                        success: (result) => {
                            let imgFileKey = ''
                            if (side == "back") {
                                imgFileKey = 'idCardPicBack'
                            } else {
                                imgFileKey = 'idCardPicFront'
                            }
                            var rawBase64 = result.data;
                            this.imageuploadFile({
                                [imgFileKey]: rawBase64
                            }).then(res => {
                                if (res.code == 200) {
                                    res.rspData = JSON.parse(res.rspData).object
                                    console.log(res)
                                    console.log(res.rspData)
                                    if (ossRes.code == 200) {
                                        this.setData({
                                            [type]: 2,
                                        });
                                        if (side == 'face') {
                                            this.data.agentFrontImg = res.rspData.idCardPicFront;
                                            this.setData({
                                                agentFrontImgUrl: ossRes.rspData,
                                            })
                                        } else {
                                            this.data.agentBackImg = res.rspData.idCardPicBack;
                                            this.setData({
                                                agentBackImgUrl: ossRes.rspData
                                            })
                                        }
                                        wx.hideLoading()
                                    } else {
                                        this.setData({
                                            [type]: 3,
                                        })
                                        wx.showToast({
                                            title: '图片上传失败',
                                            icon: 'none',
                                            duration: 3000,
                                            mask: false
                                        });
                                    }
                                } else {
                                    this.setData({
                                        [type]: 3,
                                    })
                                    wx.showToast({
                                        title: '图片上传失败',
                                        icon: 'none',
                                        duration: 3000,
                                        mask: false
                                    });
                                }

                            }).catch(err => {
                                console.log(err)
                                this.setData({
                                    [type]: 3,
                                })
                                wx.showToast({
                                    title: '图片上传失败',
                                    icon: 'none',
                                    duration: 3000,
                                    mask: false
                                });
                            })
                        },
                        fail: err => {
                            wx.hideLoading()
                            console.log('读取本地图片出错', err);
                        },
                    });
                })
            } else {
                wx.hideLoading()
                this.setData({
                    [type]: 3,
                })
            }




        }).catch(err => {
            this.setData({
                [type]: 3,
            })
            wx.showToast({
                title: '图片上传失败',
                icon: 'none',
                duration: 3000,
                mask: false
            });
        })


    },
    certifiChange(e) {
        if (this.data.isEdit) {
            return;
        }
        this.setData({
            certifiType: e.currentTarget.dataset.type
        })
    },
    //粤通卡图片上传
    imageuploadFile(obj) {
        return new Promise((resolve, reject) => {
            app.http(API.apiUploadPhotoSrc, obj).then(res => {
                resolve(res)
            }).catch(err => {
                reject(err)
            })
        })
    },
    /**
* 台湾，港澳证上传
*/
    frontimage: function (ev) {
        var _this = this;
        wx.chooseImage({
            count: 1, // 默认9 
            sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有 
            success: (res) => {
                this.setData({
                    [ev.currentTarget.dataset.type + '_success']: 1,
                });
                this.ossUploadFile(res.tempFilePaths[0]).then(ossRes => {
                    if (ossRes.code == 200) {
                        let imgFileKey = ''
                        if (ev.currentTarget.dataset.side == "back") {
                            imgFileKey = 'idCardPicBack'
                        } else {
                            imgFileKey = 'idCardPicFront'
                        }

                        // 读入本地图片
                        let tempFilePaths = ''
                        getLessLimitSizeImage('pressCanvas', res.tempFilePaths[0], 1, '750', (e) => {
                            tempFilePaths = e;
                            wx.getFileSystemManager().readFile({
                                filePath: tempFilePaths,
                                encoding: 'base64',
                                success: (result) => {
                                    var rawBase64 = result.data;
                                    let type = ev.currentTarget.dataset.type + '_success';
                                    this.imageuploadFile({
                                        [imgFileKey]: rawBase64
                                    }).then(res => {
                                        if (res.code == 200) {
                                            res.rspData = JSON.parse(res.rspData).object
                                            console.log(res.rspData)
                                            this.setData({
                                                [type]: 2,
                                            })
                                            if (this.data.certifiType == 10) {
                                                if (ev.currentTarget.dataset.side == "back") {
                                                    this.data.KO_BackImg = res.rspData.idCardPicBack;
                                                    this.setData({
                                                        KO_BackImgUrl: ossRes.rspData
                                                    })
                                                } else {
                                                    this.data.KO_FrontImg = res.rspData.idCardPicFront;
                                                    this.setData({
                                                        KO_FrontImgUrl: ossRes.rspData
                                                    })
                                                }

                                            } else {
                                                if (ev.currentTarget.dataset.side == "back") {
                                                    this.data.taiWan_BackImg = res.rspData.idCardPicBack;
                                                    this.setData({
                                                        taiWan_BackImgUrl: ossRes.rspData
                                                    })
                                                } else {
                                                    this.data.taiWan_FrontImg = res.rspData.idCardPicFront;
                                                    this.setData({
                                                        taiWan_FrontImgUrl: ossRes.rspData
                                                    })
                                                }
                                            }
                                            wx.hideLoading()
                                        } else {
                                            wx.hideLoading()
                                            this.setData({
                                                [type]: 3,
                                            })
                                        }

                                    }).catch(err => {
                                        wx.hideLoading()
                                        this.setData({
                                            [type]: 3,
                                        })
                                    })
                                },
                                fail: err => {
                                    wx.hideLoading()
                                    // console.log('读取本地图片出错', err);
                                },
                            });
                        })


                    } else {
                        wx.hideLoading()
                        this.setData({
                            [type]: 3,
                        })
                    }
                }).catch(err => {
                    wx.hideLoading()
                    this.setData({
                        [type]: 3,
                    })
                });

            }
        })
    },
    //身份证识别，调用腾讯ocr
    idCardSuccess(e) {
        wx.showLoading({
            title: '识别中...',
            mask: true,
        });
        let tempFilePaths = e.detail.image_path;
        let ocrVehicleType = e.currentTarget.dataset.type;
        let side = e.currentTarget.dataset.side;
        let type = ocrVehicleType + '_success';
        if (e.currentTarget.dataset.side == 'face') {
            if (this.data.isEdit) {
                this.setData({
                    ['idcardData.address']: e.detail.address.text
                })
            } else {
                this.setData({
                    ['idcardData.name']: e.detail.name.text,
                    ['idcardData.num']: e.detail.id.text,
                    ['idcardData.address']: e.detail.address.text
                })
            }

            this.idCardLicenseImage(ocrVehicleType, type, side, tempFilePaths)
        } else {
            let trx_id_stime = ''
            let trx_id_etime = ''
            let time = e.detail.valid_date.text.split('-')
            if (time[1] == '长期') {
                trx_id_etime = '20990101'
            } else {
                trx_id_etime = time[1]
            }

            trx_id_stime = time[0]
            this.setData({
                ['idcardData.trx_id_stime']: trx_id_stime,
                ['idcardData.trx_id_etime']: trx_id_etime,
            })
            this.idCardLicenseImage(ocrVehicleType, type, side, tempFilePaths)
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        app.getDeviceSize().then(res => {
            const { bottomLift, windowHeight } = res
            console.log(bottomLift)
            this.setData({
                bottomLift, windowHeight
            })
        })
        let userId = wx.getStorageSync('userId') || '';
        this.setData({
            userId
        })
        this.getState()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})